package com.mz.ozy.activity.shop;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mz.ozy.R;
import com.mz.ozy.adapter.SearchListAdapter;
import com.mz.ozy.adapter.SortPopAdapter;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.GoodsCategoryBean;
import com.mz.ozy.bean.GoodsListBean;
import com.mz.ozy.bean.MeBean;
import com.mz.ozy.bean.ObShopBean;
import com.mz.ozy.bean.TwoTitleBean;
import com.mz.ozy.mvp.presenter.GoodsListPresenter;
import com.mz.ozy.mvp.view.GoodsListContract;
import com.mz.ozy.utils.Utils;
import com.mz.ozy.utils.glideUtils.GlideUtils;
import com.mz.ozy.widget.CustomPopWindow;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class TopicListActivity extends BaseActivity<GoodsListContract.View, GoodsListPresenter> implements GoodsListContract.View {

    CustomPopWindow mGridPopWindow;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout mSmartRefreshLayout;
    @BindView(R.id.gridview)
    RecyclerView mGridview;
    @BindView(R.id.ll_no_data)
    LinearLayout llNoData;
    @BindView(R.id.dragview)
    ImageView mDragview;
    @BindView(R.id.rele)
    RelativeLayout rele;
    @BindView(R.id.logoIv)
    ImageView logoIv;
    private ImageView ivBannerPager;

    private List<GoodsListBean.GoodsPageBean.PageItemsBean> mBeanList = new ArrayList<>();
    private SearchListAdapter mAdapter;
    private int tag;
    private int page = 1;
    private String id = "";
    private String type = "";
    private String orderBy = "0";//按照什么排序
    private String orderType = "0";//0-升序 1-倒序
    private String name;
    private List<GoodsCategoryBean.CateListBean> mCateList;
    private String content;

    private int flag = 0;
    private float mOriginalX, mOriginalY;//手指按下时的初始位置
    private float lastX, lastY; //最后一次触摸事件的坐标
    private int containerWidth, containerHeight;    //容器宽高
    private MeBean mMeBean;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_topic_list);
        ButterKnife.bind(this);
        initTitle();
        id = getIntent().getStringExtra("id");
        type = getIntent().getStringExtra("type");
        name = getIntent().getStringExtra("name");
        content = getIntent().getStringExtra("content");

        if (!TextUtils.isEmpty(name)) {
            tvTitle.setText(name);
        } else if (!TextUtils.isEmpty(content)) {
            tvTitle.setText(content);
        }
        rightImage.setVisibility(View.VISIBLE);
        rightImage.setImageResource(R.mipmap.icon_right_search);
        initView();
        initLottery();
        logoIv.setVisibility(View.GONE);
        rightImage.setVisibility(View.GONE);
        mPresenter.getGoodsTopic(this);
    }

    private void initLottery() {
        rele.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                //不能直接在onCreate()方法中得到宽高,会得到0,所以注册视图树的观察者来得到宽高
                //OnPreDrawListener是当一个视图树将要绘制时，所要调用的回调函数的接口类
                containerWidth = rele.getWidth();
                containerHeight = rele.getHeight();
                return true;
            }
        });
        mDragview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        //记录触摸时的坐标,这里为什么要用getRawX()和getRawY()相信理解getX(),getY()和getRawX(),getRawY()的区别就知道为什么了
                        lastX = motionEvent.getRawX();
                        lastY = motionEvent.getRawY();
                        mOriginalX = motionEvent.getRawX();
                        mOriginalY = motionEvent.getRawY();
                        //return true对事件进行拦截,不继续下发,防止继续响应onClick事件.
                        return true;
                    case MotionEvent.ACTION_MOVE:
                        //每次移动的距离
                        float distanceX = motionEvent.getRawX() - lastX;
                        float distanceY = motionEvent.getRawY() - lastY;

                        //控件将要移动到的位置,先计算一下,不在ofFloat()方法中再计算是因为要防止控件移动到容器之外.
                        float nextX = mDragview.getX() + distanceX;
                        float nextY = mDragview.getY() + distanceY;
                        //如果将要移动到的 x 轴坐标小于0,则等于0,防止移出容器左边
                        if (nextX < 0)
                            nextX = 0;
                        //防止移出容器右边
                        if (nextX > containerWidth - mDragview.getWidth())
                            nextX = containerWidth - mDragview.getWidth();
                        //防止移出容器顶边
                        if (nextY < 0)
                            nextY = 0;
                        //防止移出容器底边
                        if (nextY > containerHeight - mDragview.getHeight())
                            nextY = containerHeight - mDragview.getHeight();
                        //利用属性动画改变控件的x,y坐标
                        ObjectAnimator mObjectAnimatorX = ObjectAnimator.ofFloat(mDragview, "x", mDragview.getX(), nextX);
                        ObjectAnimator mObjectAnimatorY = ObjectAnimator.ofFloat(mDragview, "y", mDragview.getY(), nextY);
                        AnimatorSet mAnimatorSet = new AnimatorSet();
                        mAnimatorSet.playTogether(mObjectAnimatorX, mObjectAnimatorY);
                        mAnimatorSet.setDuration(0);
                        mAnimatorSet.start();
                        //移动完之后记录当前坐标
                        lastX = motionEvent.getRawX();
                        lastY = motionEvent.getRawY();
                        break;
                    case MotionEvent.ACTION_UP:
                        if (Math.abs(motionEvent.getRawX() - mOriginalX) <
                                Utils.dp2px(TopicListActivity.this, 3) &&
                                Math.abs(motionEvent.getRawY() - mOriginalY) <
                                        Utils.dp2px(TopicListActivity.this, 3)) {
                            CarActivity.go(TopicListActivity.this);
                        }
                        break;
                }
                return false;
            }
        });
    }

    private void initView() {
        mGridview.setLayoutManager(new GridLayoutManager(this, 2));
        mAdapter = new SearchListAdapter(mBeanList);
        mGridview.setAdapter(mAdapter);
        final View preOrderView = View.inflate(this, R.layout.topic_banner_pager, null);
        mAdapter.addHeaderView(preOrderView);
        ivBannerPager = preOrderView.findViewById(R.id.iv_bannerPager);
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                //商品详情
                final GoodsListBean.GoodsPageBean.PageItemsBean item = mAdapter.getItem(position);
                switch (view.getId()) {
                    case R.id.ll_item_view: {
                        Intent intent = new Intent(TopicListActivity.this, ShopDetailActivity.class);
                        intent.putExtra("goodsId", item.getId() + "");
                        startActivity(intent);
                        break;
                    }
                    case R.id.iv_search_car: {
                        Intent intent = new Intent(TopicListActivity.this, ShopDetailActivity.class);
                        intent.putExtra("goodsId", item.getId() + "");
                        intent.putExtra("show", 1);
                        startActivity(intent);
                        break;
                    }
                }
            }
        });
        mSmartRefreshLayout.setEnableAutoLoadmore(true);
        mSmartRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                tag = 1;
                page = page + 1;
                mPresenter.onSearchGoodByTopic(TopicListActivity.this, id, page + "");
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                searchListByRefresh();
            }
        });
        if (!TextUtils.isEmpty(id) || !TextUtils.isEmpty(content)) {
            mSmartRefreshLayout.autoRefresh();
        }
    }

    private void searchListByRefresh() {
        tag = 0;
        page = 1;
        mPresenter.onSearchGoodByTopic(TopicListActivity.this, id, page + "");
    }

    @OnClick({R.id.ll_title, R.id.rightImage})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_title: {
                if ("0".equals(type)) {
                    if (mGridPopWindow != null) {
                        mGridPopWindow.showAsDropDown(titleBar);
                    } else {
                        showPopListView();
                    }
                }
                break;
            }
            case R.id.rightImage:       //搜索
                startActivity(new Intent(this, SearchActivity.class));
                finish();
                break;
        }
    }

    private void showPopListView() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_brand_grid, null);
        //处理popWindow 显示内容
        handleGridView(contentView);
        //创建并显示popWindow
        mGridPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)//显示大小
                .create()
                .showAsDropDown(titleBar);
    }


    private SortPopAdapter mBrandPopGridAdapter;

    private void handleGridView(View contentView) {
        RecyclerView gridview = contentView.findViewById(R.id.recyclerView);
        gridview.setLayoutManager(new LinearLayoutManager(this));
        contentView.findViewById(R.id.view).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mGridPopWindow != null) {
                    mGridPopWindow.dissmiss();
                }
            }
        });
        if (mCateList != null) {
            mBrandPopGridAdapter = new SortPopAdapter(mCateList, id);
            gridview.setAdapter(mBrandPopGridAdapter);
            mBrandPopGridAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    final GoodsCategoryBean.CateListBean item = (GoodsCategoryBean.CateListBean) mBrandPopGridAdapter.getItem(position);
                    tvTitle.setText(item.getName());
                    mGridPopWindow.dissmiss();
                    mBrandPopGridAdapter.setSelectPosition(position);
                    mBrandPopGridAdapter.notifyDataSetChanged();
                    id = String.valueOf(item.getId());
                    mSmartRefreshLayout.autoRefresh();
                }
            });
        }
    }

    @Override
    public void getSearchGoodSuccess(GoodsListBean bean) {
        if ("2".equals(type)) {
            GlideUtils.loadRoundImg(this, ivBannerPager, bean.getImg(), R.mipmap.default_main_banner, 4);
        }
        if (tag == 0) {
            mSmartRefreshLayout.setLoadmoreFinished(false);
            mSmartRefreshLayout.finishRefresh();
            mBeanList.clear();
            if (bean.getP().getPageItems().size() == 0) {
                llNoData.setVisibility(View.VISIBLE);
            } else {
                llNoData.setVisibility(View.GONE);
            }
        } else if (tag == 1) {
            mSmartRefreshLayout.finishLoadmore();
        }
        mBeanList.addAll(bean.getP().getPageItems());
        mAdapter.notifyDataSetChanged();
        if (bean.getP().getPageItems().size() == 0 || bean.getP().getPageSize() * bean.getP().getPageNumber() >= bean.getP().getPageTotle()) {
            mSmartRefreshLayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
        }
    }

    @Override
    public void getGoodsCategoryData(GoodsCategoryBean bean) {
        final List<GoodsCategoryBean.CateListBean> cateList = bean.getCateList();
        mCateList = cateList;
        if (mCateList != null && mCateList.size() > 0) {
            if (TextUtils.isEmpty(content)) {
                if (TextUtils.isEmpty(id)) {
                    id = mCateList.get(0).getId() + "";
                    mSmartRefreshLayout.autoRefresh();
                }
                if (TextUtils.isEmpty(name)) {
                    name = mCateList.get(0).getName();
                    tvTitle.setText(name);
                }
            }
        }
    }

    @Override
    public void getGoodsTopicData(GoodsCategoryBean bean) {
        final List<GoodsCategoryBean.CateListBean> cateList = bean.getCateList();
        mCateList = cateList;
        if (mCateList != null && mCateList.size() > 0) {
            if (TextUtils.isEmpty(content)) {
                if (TextUtils.isEmpty(id)) {
                    id = mCateList.get(0).getId() + "";
                    mSmartRefreshLayout.autoRefresh();
                }
                if (TextUtils.isEmpty(name)) {
                    name = mCateList.get(0).getName();
                    tvTitle.setText(name);
                }
            }
        }
    }

    @Override
    public void getTwoTitleSuccess(TwoTitleBean bean) {

    }

    @Override
    public void showListData(GoodsListBean bean) {

    }
//    @Override
//    public void getMyMeInfoSuccess(MeBean bean) {
//        mMeBean = bean;
//    }
}
